<template>
  <div class="outter">
    <!-- 一排按钮最上面的 -->
    <div class="bottonheader">
      <div class="buttons">
        <a-button
          type="primary"
          :disabled="!hasSelectedOpen"
          :loading="loading"
          @click="domore('open')"
        >
          开台
        </a-button>
        <a-button
          type="dashed"
          :disabled="!hasSelectedOther"
          :loading="loading"
          @click="domore('reset')"
        >
          置空
        </a-button>
        <a-button
          type="primary"
          :disabled="!hasSelected"
          :loading="loading"
          @click="domore('close')"
        >
          关台
        </a-button>
        <a-button
          type="danger"
          :disabled="!hasSelected"
          :loading="loading"
          @click="domore('deletet')"
        >
          删除
        </a-button>
      </div>
      <a-button :loading="loading" @click="addvisible=true"> 添加桌台 </a-button>
    </div>
    <div style="height:450px;overflow:scroll;">
      <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :pagination="false"
      :data-source="data"
      bordered
      :fixed="true"
      :loading="tableLoading"
    >
    <!-- 标签部分和操作部分 -->
      <span slot="state" slot-scope="state">
        <a-tag :color="state.color">{{ state.text }}</a-tag>
      </span>
      <span slot="method" slot-scope="method, record">
        <a-button
          :loading="method.onOrNoLoading"
          @click="open(record)"
          size="small"
          v-if="!method.onOrNo"
          type="primary"
        >
          开台
        </a-button>
        <a-button
          :loading="method.onOrNoLoading"
          @click="close(record)"
          size="small"
          type="primary"
          v-else
        >
          关台
        </a-button>
        <a-divider type="vertical" />
        <a-button
          :loading="method.resetLoading"
          :disabled="record.state.text !== '使用中'"
          @click="reset(record)"
          size="small"
          type="dashed"
        >
          置空
        </a-button>
        <a-divider type="vertical" />
        <a-button
          :loading="method.deleteLoading"
          @click="deletet(record)"
          size="small"
          type="danger"
        >
          删除
        </a-button>
      </span>
      <!-- 桌号旁边的查找 -->
      <div
        slot="filterDropdown"
        slot-scope="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
        style="padding: 8px"
      >
        <a-input
          v-ant-ref="(c) => (searchInput = c)"
          :placeholder="`查找桌号`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block"
          @change="
            (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
          "
          @pressEnter="
            () => handleSearch(selectedKeys, confirm, column.dataIndex)
          "
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          查找
        </a-button>
        <a-button
          size="small"
          style="width: 90px"
          @click="() => handleReset(clearFilters)"
        >
          重置
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />
      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
              >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>
    </a-table>
    </div>
    <!-- 添加桌台弹出框 -->
    <a-modal
      title="添加桌台"
      :visible="addvisible"
      :confirm-loading="confirmLoading"
      @ok="submitForm('ruleForm')"
      @cancel="handleCancel"
      okText="确认"
      cancelText="取消"
    >
      <a-form-model
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        v-bind="layout"
      >
        <a-form-model-item has-feedback label="桌号" prop="value">
          <a-input v-model="ruleForm.value" autocomplete="off" />
        </a-form-model-item>
         <a-form-model-item label="大小" prop="resource">
      <a-radio-group v-model="ruleForm.resource">
        <a-radio value="大桌">
          大桌
        </a-radio>
        <a-radio value="中桌">
          中桌
        </a-radio>
      </a-radio-group>
    </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {deleteTable,addTable,updateTalbeState,getAllTable} from "@/api/dinnerTable";
// 定义四列属性
const columns = [
  {
    title: "桌号",
    dataIndex: "name",
    width: "20%",
    align: "center",
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender",
    },
    onFilter: (value, record) =>
      record.name.toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => {
          this.searchInput.focus();
        }, 0);
      }
    },
  },
  {
    title: "大小",
    dataIndex: "size",
    align: "center",
    width: "15%",
    filters: [
      {
        text: "中桌",
        value: "中桌",
      },
      {
        text: "大桌",
        value: "大桌",
      },
    ],
    onFilter: (value, record) => record.size.indexOf(value) === 0,
  },
  {
    title: "状态",
    dataIndex: "state",
    width: "20%",
    scopedSlots: { customRender: "state" },
    align: "center",
    filters: [
      {
        text: "使用中",
        value: "使用中",
      },
      {
        text: "可使用",
        value: "可使用",
      },
      {
        text: "已停用",
        value: "已停用",
      },
    ],
    onFilter: (value, record) => record.state.text.indexOf(value) === 0,
  },
  {
    title: "操作",
    dataIndex: "method",
    align: "center",
    scopedSlots: { customRender: "method" },
  },
];


export default {
  data() {
    // 定义弹出框的表单规则
    let validateValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入桌号"));
      } else if (value.length > 3) {
        callback(new Error("桌号不应该过长"));
      } else if (
        this.data.some((item) => {
          return item.name.slice(1) == value;
        })
      ) {
        callback(new Error("已有该桌号"));
      } else if (!/[0-9]/.test(value)) {
        callback(new Error("桌号应该包含数字"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        value: "",
        resource: '',
      },
      rules: {
        value: [{required: true, validator: validateValue, trigger: "change" }],
        resource: [
          { required: true, message: '请选择桌号大小', trigger: 'change' },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      addvisible: false,
      confirmLoading: false,
      data:[],
      columns,
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      searchText: "",
      tableLoading:false
    };
  },
  created(){
    this.initWebSocket()
    this.getData()
  },

  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
    //主要是只有所选项都必须为可重置才可以显示重置按钮
    hasSelectedOther(){
      if(this.selectedRowKeys.length === 0) return false
      let flag=true
      this.data.map(item=>{
                if(flag==false) return
                for(let i=0;i<this.selectedRowKeys.length;i++){
                  if(item.key===this.selectedRowKeys[i]){
                    if(item.state.text=="使用中"){
                      flag=true
                    }
                    else{
                      flag=false
                      break 
                    }
                  }
                }
              })
              return flag
    },
     hasSelectedOpen(){
      if(this.selectedRowKeys.length === 0) return false
      let flag=true
      this.data.map(item=>{
                if(flag==false) return
                for(let i=0;i<this.selectedRowKeys.length;i++){
                  if(item.key===this.selectedRowKeys[i]){
                    if(item.state.text=="已停用"){
                      flag=true
                    }
                    else{
                      flag=false
                      break 
                    }
                  }
                }
              })
              return flag
    }
  },
  methods: {
    getData(){
      this.tableLoading=true
    getAllTable().then((res)=>{
      res.data.map(item=>{
        item.name=item.seatNo
        item.state=item.state[0]
        item.method=item.method[0]
      })
      this.data=res.data
      this.tableLoading=false
    })
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var url ="wss://miswestrestaurant.xyz/websocket"
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen: function () {
      console.log("WebSocket连接成功");
    },
    websocketonerror: function (e) {
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage: function (e,data) {
      console.log("WebSocket接受消息");
      console.log(e)
      
      this.getData()
      
    },
    
    destroyed: function () {
      // 离开页面生命周期函数
      this.websocketclose();
    },
    //四个多选项操作
    domore(method){
      this.$confirm({
          title: '提示',
          content: '该操作仅会对选中且满足该操作条件的项进行处理，请问是否继续?',
          okText: '确认',
          cancelText: '取消',
          onOk:()=>{
              this.data.map(item=>{
                for(let i=0;i<this.selectedRowKeys.length;i++){
                  if(item.key===this.selectedRowKeys[i]){
                    this[method](item)
                  }
                }
              })
          
          },
          onCancel() {
          },
        });
    },
    handleCancel() {
      this.addvisible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          addTable({size:this.ruleForm.resource==="大桌"?1:2,seatNo:this.ruleForm.value}).then((res)=>{
            if(res.code===200){
              this.confirmLoading = false;
            this.data.push({
              key: this.ruleForm.value,
              name: ((this.ruleForm.resource==="大桌"?'A':'B')+this.ruleForm.value),
              size: this.ruleForm.resource,
              state: { color: "grey", text: "已停用" },
              method: {
                onOrNo: false,
                onOrNoLoading: false,
                resetLoading: false,
                deleteLoading: false,
              },
            });
            

            this.$message.success("成功添加");
            this.addvisible=false
            }
          })
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    open(target) {
      target.method.onOrNoLoading = true;
      updateTalbeState({keys:[target.name],state:0}).then(res=>{
        target.method.onOrNoLoading = false;
        if(res.code===200){
        target.state = { color: "green", text: "可使用" };
        target.method.onOrNo = true;
        }
      })
    },
    close(target) {
      target.method.onOrNoLoading = true;
        
        updateTalbeState({keys:[target.name],state:-1}).then(res=>{
          target.method.onOrNoLoading = false;
        if(res.code===200){
          target.state = { color: "grey", text: "已停用" };
          target.method.onOrNo = false;
        }
      })
    },
    reset(target) {
      target.method.resetLoading = true;
      
        
        updateTalbeState({keys:[target.name],state:0}).then(res=>{
          target.method.resetLoading = false;
        if(res.code===200){

        target.state = { color: "green", text: "可使用" };
        target.method.onOrNo = true;
        }
      })

    },
    deletet(target) {
      target.method.deleteLoading = true;
        
        deleteTable({seatNo:target.name}).then(res=>{
          target.method.resetLoading = false;
        if(res.code===200){

        this.data = this.data.filter((item) => item.key !== target.key);
        }
      })

    },

    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },

    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
    },
  },
};
</script>

<style scoped>
.outter {
  padding: 20px 10px;
}
.bottonheader {
  widows: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.buttons {
  width: 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.nima {
  width: 100%;
  height: 420px;
  background: rgb(217, 220, 223);
}
</style>
